<template>
  <div class="all-page">
    <section class="layer">
      <div class="box" style="padding-bottom:6px;">
        <div class="box-body">
          <el-form ref="prewForm" :model="prewForm" label-width="120px">
            <el-row :gutter="12">
              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label="请选择下载类型">
                  <el-select v-model="prewForm.fileType" placeholder="请选择" style="width:100%">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="16" :xl="18">
                <el-button v-no-more-click type="primary" style="float: right" @click="printHtml">打印</el-button>
                <el-button v-no-more-click type="primary" @click="templDownload">下载</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </section>
    <section class="layer" style="margin-top:0px;height:calc(100% - 56px);">
      <div class="box" style="border:0px;">
        <div class="box-body pdf-box" style="height:100%;overflow:auto;">
          <!-- <div id="previewHtml" v-html="previewHtml"/> -->
          <p style="position:fixed;z-index:1;">
            <!-- 上一页 -->
            <span :class="{grey: currentPage==1}" class="turn" @click="changePdfPage(0)">上一页</span>
            {{ currentPage }} / {{ pageCount }}
            <!-- 下一页 -->
            <span :class="{grey: currentPage==pageCount}" class="turn" @click="changePdfPage(1)">下一页</span>
            <el-button
              :class="{select:idx==0}"
              icon="el-icon-zoom-in"
              type="primary"
              @touchstart="idx=0"
              @touchend="idx=-1"
              @click="scaleD">
              放大
            </el-button>
            <el-button
              :class="{select:idx==1}"
              icon="el-icon-zoom-out"
              type="primary"
              @touchstart="idx=1"
              @touchend="idx=-1"
              @click="scaleX">
              缩小
            </el-button>
          </p>
          <pdf
            v-loading="pdfLoading"
            ref="pdf"
            :page="currentPage"
            :src="src"
            @num-pages="pageCount=$event"
            @page-loaded="currentPage=$event"
            @loaded="loadPdfHandler"
            @error="getpdfError"/>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import ApiObj from '@/api/template-management'
import pdf from 'vue-pdf'
export default {
  components: {
    pdf
  },
  data() {
    return {
      ruleForm: {
        reportParaList: [
          {
            paraName: ''
          }
        ]
      },
      prewForm: {
        fileType: '1'
      },
      options: [{
        value: '1',
        label: 'pdf'
      },
      {
        value: '2',
        label: 'excel'
      }],
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      fileType: 'pdf', // 文件类型
      src: '',
      pdfLoading: true,
      scale: 60, // 放大系数
      idx: -1
    }
  },
  mounted() {
    this.getPreviewPage()
    this.getReportTmplDetail()
  },
  methods: {
    // 打印
    printHtml() {
      this.$refs.pdf.print()
    },
    getReportTmplDetail() {
      let params = {
        tmplId: this.getParamsByUrl().tmplId
      }
      ApiObj.templateGetReportTmplDetail(params).then(res => {
        if (res.data.code === 0) {
          this.ruleForm = res.data.data
          this.ruleForm.fileType = this.prewForm.fileType
          Object.keys(this.getParamsByUrl()).forEach(item => {
            this.ruleForm.reportParaList.forEach(ele => {
              if (item === ele.paraName) {
                ele.paraValue = this.getParamsByUrl()[item]
              }
            })
          })
        }
      })
    },
    // 下载
    templDownload() {
      let params = this.ruleForm
      params.fileType = this.prewForm.fileType
      ApiObj.templDownload(params).then(res => {
        let filename = res.headers['content-disposition'].split(';')[1].split('=')[1]
        let url
        if (this.prewForm.fileType === '1') {
          url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }))
        } else {
          url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/octet-stream' }))
        }
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
      })
    },
    // 获取预览页面
    getPreviewPage() {
      // ApiObj.printTmpl({}).then(res => {
      //   if (res.data.code === 0) {
      let params = this.getParamsByUrl()
      this.src = `${process.env.BASE_API}/report-server/reportTemplateController/print.action?`
      for (let key in params) {
        this.src += `&${key}=${params[key]}`
      }
      //   } else {
      //     this.$alert(
      //       `<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`,
      //       {
      //         confirmButtonText: '确定',
      //         dangerouslyUseHTMLString: true,
      //         type: 'error'
      //       }
      //     )
      //   }
      // })
    },
    getParamsByUrl() {
      var url = window.location.href
      var paraString = url.substring(url.indexOf('?') + 1, url.length).split('&')
      var paraObj = {}
      var nameValue
      for (var i = 0; i < paraString.length; i++) {
        nameValue = paraString[i]
        var name = nameValue.substring(0, nameValue.indexOf('='))
        var value = nameValue.substring(nameValue.indexOf('=') + 1, nameValue.length)
        if (value.indexOf('#') > -1) {
          value = value.split('#')[0]
        }
        paraObj[name] = value
      }
      return paraObj
    },
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
      }
    },
    // pdf加载时
    loadPdfHandler(e) {
      this.currentPage = 1 // 加载的时候先加载第一页
      this.pdfLoading = false

      this.$refs.pdf.$el.style.width = parseInt(this.scale) + '%'
    },
    // 放大
    scaleD() {
      this.scale += 5
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + '%'
    },
    // 缩小
    scaleX() {
      this.scale += -5
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + '%'
    },
    // 获取pdf时异常
    getpdfError(e) {
      if (e.status === 500) {
        this.$alert(
          `<div class="myalert-header">操作失败</div><div class="myalert-content">报表生成异常</div></div>`,
          {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
            type: 'error'
          }
        )
        this.pdfLoading = false
      }
    }
  }
}

</script>

<style scoped lang="scss">
.pdf-box{
  &>span{
    margin:0 auto;
  }
}
.copy-button{
  cursor: pointer;
}
.all-page{

  height: 100%!important;
  .el-form .el-form-item{
    margin-bottom:0px;
  }
  /deep/.el-dialog{
    height: 100%!important;
  }
   /deep/ .el-dialog__body{
   max-height: 100%;
 }
 #previewHtml{
  height: 100%;
   overflow-y: auto;
 }
 .turn{
  cursor:pointer;
 }
}
</style>
